const SegmentTree = require("../template")

function testSegmentTreeRangeQueries() {
  const arr = [1, 3, 5, 7, 9, 11, 13, 15]
  const st = new SegmentTree(arr)

  console.log(
    "1. 区间查询基础测试:",
    (() => {
      return st.getRangeSum(0, 3) === 16 && // 1+3+5+7=16
             st.getRangeSum(2, 5) === 32 && // 5+7+9+11=32
             st.getRangeSum(0, 7) === 64 // 1+3+5+7+9+11+13+15=64
    })()
  )

  console.log(
    "2. 单点区间查询测试:",
    (() => {
      return st.getRangeSum(0, 0) === 1 &&
             st.getRangeSum(3, 3) === 7 &&
             st.getRangeSum(7, 7) === 15
    })()
  )

  console.log(
    "3. 重叠区间查询测试:",
    (() => {
      const sum1 = st.getRangeSum(1, 4)
      const sum2 = st.getRangeSum(2, 5)
      const sum3 = st.getRangeSum(3, 6)
      return sum1 === 24 && sum2 === 32 && sum3 === 40
    })()
  )

  console.log(
    "4. 边界区间查询测试:",
    (() => {
      return st.getRangeSum(0, 1) === 4 &&
             st.getRangeSum(6, 7) === 28 &&
             st.getRangeSum(0, 7) === 64
    })()
  )

  console.log(
    "5. 区间查询一致性测试:",
    (() => {
      const sum1 = st.getRangeSum(0, 7)
      const sum2 = st.getRangeSum(0, 3) + st.getRangeSum(4, 7)
      return sum1 === sum2
    })()
  )

  console.log(
    "6. this上下文区间查询测试:",
    (() => {
      const stObj = {
        multiplier: 2,
        processRangeQuery: function(arr, l, r) {
          const st = new SegmentTree(arr)
          const sum = st.getRangeSum(l, r)
          return sum * this.multiplier
        }
      }
      return stObj.processRangeQuery([1, 2, 3, 4], 0, 3) === 20 // (1+2+3+4)*2=20
    })()
  )

  console.log(
    "7. 复杂对象this绑定区间查询测试:",
    (() => {
      const stConfigObj = {
        config: { threshold: 10 },
        processWithConfig: function(arr, l, r) {
          const st = new SegmentTree(arr)
          const sum = st.getRangeSum(l, r)
          return sum > this.config.threshold
        }
      }
      return stConfigObj.processWithConfig([1, 2, 3, 4, 5], 0, 4) === true
    })()
  )

  console.log(
    "8. 区间查询性能测试:",
    (() => {
      const largeArr = Array.from({ length: 1000 }, (_, i) => i + 1)
      const perfSt = new SegmentTree(largeArr)
      const start = performance.now()
      for (let i = 0; i < 100; i++) {
        perfSt.getRangeSum(0, 999)
      }
      const end = performance.now()
      return (end - start) < 1000
    })()
  )

  console.log(
    "9. 区间查询边界测试:",
    (() => {
      const boundarySt = new SegmentTree([1])
      return boundarySt.getRangeSum(0, 0) === 1
    })()
  )

  console.log(
    "10. 区间查询复杂测试:",
    (() => {
      const complexSt = new SegmentTree([1, 2, 3, 4, 5, 6, 7, 8])
      const sum1 = complexSt.getRangeSum(0, 2)
      const sum2 = complexSt.getRangeSum(3, 5)
      const sum3 = complexSt.getRangeSum(6, 7)
      const totalSum = complexSt.getRangeSum(0, 7)
      return sum1 === 6 && sum2 === 15 && sum3 === 15 && totalSum === 36
    })()
  )
}

testSegmentTreeRangeQueries()
